package com.jack.xiaoer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jack.xiaoer.constant.ProductStateEnum;
import com.jack.xiaoer.dao.ProductMapper;
import com.jack.xiaoer.entity.Product;
import com.jack.xiaoer.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/13.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product createProduct(Optional<Product> product) {
        if (!product.isPresent())
            return null;

        final Product productEntity = product.get();
        productEntity.setState(ProductStateEnum.NORMAL);
        productEntity.setGmtCreate(Instant.now());
        productEntity.setGmtModified(Instant.now());

        int row = productMapper.insert(productEntity);

        if (row > 0) {
            return productEntity;
        }
        return null;
    }

    @Override
    public IPage<Product> listProduct(Long shopId, Long cateId, int pageNum, int pageSize) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (shopId != null && shopId > 0) {
            queryWrapper.eq("shop_id", shopId);
        }
        if (cateId != null && cateId > 0) {
            queryWrapper.eq("category_id", cateId);
        }
        queryWrapper.eq("state", ProductStateEnum.NORMAL);
        Page<Product> page = new Page<>(pageNum, pageSize);

        IPage<Product> productPage = productMapper.selectPage(page, queryWrapper);

        return productPage;
    }

}
